package com.heima.comment.service.iml;

import com.heima.aliyun.GreenTextScan;
import com.heima.comment.service.CommentRepayService;
import com.heima.common.exception.CustException;
import com.heima.feigins.ApUserFeigin;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.dtos.CommentSaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentLike;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vos.ApCommentRepayVO;
import com.heima.model.comment.vos.ApCommentVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    ApUserFeigin apUserFeigin;

    /*
    * 查看更多评论回复列表
    * */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {

        //1. 校验参数

       //1.1 评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        // 校验size
        if (dto.getSize()==0 || dto.getSize()==null){
            dto.setSize(10);
        }
        if (dto.getMinDate()==null){
            dto.setMinDate(new Date());
        }
        //2. 条件查询评论回复信息
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate())).limit(dto.getSize())
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        //3. 检查是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            // 4. 如果未登录直接返回评论列表
            return ResponseResult.okResult(apCommentRepays);
        }
        //5. 如果登录了 需要检查在当前评论列表中 哪些评论登陆人点赞过
        //遍历集合，根据评论id查询出改评论都被谁点赞过，
        //获取文章评论的所有id  ,使用流
        List<String> apCommentRepayIds = apCommentRepays.stream().map(map -> map.getId()).collect(Collectors.toList());
        Query query1 = Query.query(Criteria.where("commentRepayId").in(apCommentRepayIds).and("authorId").is(user.getId()));
        //查询登录用户点赞的记录
        List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(query1, ApCommentRepayLike.class);
        //5.2 遍历评论列表, 将每一个评论  ApComment 转成 ApCommentVO
        List<ApCommentRepayVO> apCommentRepayVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(apCommentRepays) && !CollectionUtils.isEmpty(apCommentRepayLikes)) {
            for (ApCommentRepay apCommentRepay : apCommentRepays) {
                ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
                BeanUtils.copyProperties(apCommentRepay,apCommentRepayVO);
                //遍历当前点赞表
                for (ApCommentRepayLike apCommentRepayLike : apCommentRepayLikes) {
                    if (apCommentRepay.getId().equals(apCommentRepayLike.getCommentRepayId())){
                        apCommentRepayVO.setOperation((short) 0);
                        break;
                    }
                }
                apCommentRepayVos.add(apCommentRepayVO);
            }
            return ResponseResult.okResult(apCommentRepayVos);
        }
        return ResponseResult.okResult(apCommentRepays);

    }
    /*
    * 保存回复评论的信息
    * */
    @Autowired
    GreenTextScan greenTextScan;
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        //1. 参数校验:
       // 是否登录  评论id是否为空  内容是否为空  内容是否大于140个字符
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN,"用户未登录");
        }
        //2.回复内容安全校验，检查到有问题抛异常
        boolean flag=true;
        try {
            Map map = greenTextScan.greenTextScan(dto.getContent());
            String suggestion = (String) map.get("suggestion");
            switch (suggestion) {
                case "block":
                    log.info("阿里云文本审核不通过");
                    flag=false;
                    break;
                case "review":
                    log.info("阿里云文本审核不确定，有擦边球行为");
                    flag=false;
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("阿里云文本审核出现异常，异常原因    "+e.getMessage());
            flag=false;
        }
        if (!flag){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"阿里云检测有问题，内容检测未通过");
        }
        // 3. 远程查询当前登陆用户信息
        ResponseResult<ApUser> apUserById = apUserFeigin.findApUserById(user.getId());
        if (!apUserById.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"ApUserFeigin远程调用出现错误");
        }
        ApUser data = apUserById.getData();
        if (data == null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"App用户信息不存在");
        }
        //3.根据评论id查询评论信息  检查是否存在
        Query query = Query.query(Criteria.where("id").is(dto.getCommentId()));
        ApComment one = mongoTemplate.findOne(query, ApComment.class);
        if (one ==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"评论信息不存在");
        }
            //4评论信息存在，方能回复评论信息。保存评论回复信息
            ApCommentRepay apCommentRepay = new ApCommentRepay();
            apCommentRepay.setCommentId(dto.getCommentId());
            apCommentRepay.setContent(dto.getContent());
            apCommentRepay.setCreatedTime(new Date());
            apCommentRepay.setUpdatedTime(new Date());
            apCommentRepay.setAuthorId(user.getId());
            apCommentRepay.setAuthorName(data.getName());
            apCommentRepay.setLikes(0);
            mongoTemplate.insert(apCommentRepay);
            //5.修改评论信息中回复数量 + 1
            one.setReply(one.getReply()+1);
            one.setUpdatedTime(new Date());
            mongoTemplate.save(one);
        return ResponseResult.okResult();
    }

    /*
    * 保存回复的点赞信息
    * */
    @Override
    public ResponseResult commentRepayLike(CommentRepayLikeDTO dto) {

        //1. 校验参数

        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN, "用户未登录");
        }
        Query query = Query.query(Criteria.where("id").is(dto.getCommentRepayId()));
        ApCommentRepay one = mongoTemplate.findOne(query, ApCommentRepay.class);
        if (one ==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"评论回复信息不存在");
        }
        //2. 如果是点赞  判断是否点过赞
        Query query1 = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(dto.getCommentRepayId()));
        ApCommentRepayLike one1 = mongoTemplate.findOne(query1, ApCommentRepayLike.class);
        if (dto.getOperation().intValue()==0){
            if (one1==null){
                ApCommentRepayLike apCommentRepayLike = new ApCommentRepayLike();
                apCommentRepayLike.setAuthorId(user.getId());
                apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
                apCommentRepayLike.setOperation((short) 0);
                mongoTemplate.save(apCommentRepayLike);

                // 并修改评论信息的点赞数量( + 1)
                one.setLikes(one.getLikes()+1);
                one.setUpdatedTime(new Date());
                mongoTemplate.save(one);
            }else {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST,"请勿重复点赞");
            }
        }else {
            //删除点赞信息
            mongoTemplate.remove(one1);
            // 并修改评论信息的点赞数量( - 1) , 要判断下别减成负数
            if (one.getLikes()>0) {
                one.setLikes(one.getLikes() - 1);
            }
            one.setUpdatedTime(new Date());
            mongoTemplate.save(one);
        }

        //5. 返回结果时，需要返回点赞点赞数量  返回的key要求必须是:  likes
        HashMap<String, Object> map = new HashMap<>();
        map.put("likes",one.getLikes());
        ResponseResult result = ResponseResult.okResult(map);
        //result.setHost(webSite);
        return result;
    }
}
